<?php

class Filter extends Data
{
    protected $model;
    protected $htmlOptions=array(
        'model'=>false,
        'type'=>'text',
        'elementId'=>'',
        'class'=>'',
        'values'=>array(),
        'onkeyup'=>'',
        'onchange'=>'',
    );

    public function __construct($params=array())
    {
        $this->setParams($params);

        foreach(Sys::app()->request->params as $name=>$value){
            if(strpos($value,'like ')!==false) $this->htmlOptions['values'][$name]=str_replace('like ','',$value);
            elseif(strpos($value,'like--')!==false) $this->htmlOptions['values'][$name]=str_replace('like--','',$value);
            elseif(strpos($value,'like- ')!==false) $this->htmlOptions['values'][$name]=str_replace('like- ','',$value);
            elseif(strpos($value,'like-')!==false) $this->htmlOptions['values'][$name]=str_replace('like-','',$value);
            elseif(strpos($value,'like - ')!==false) $this->htmlOptions['values'][$name]=str_replace('like - ','',$value);
            elseif(strpos($value,'like -')!==false) $this->htmlOptions['values'][$name]=str_replace('like -','',$value);
        }
    }

    public function createFilterField($name='',$link='',$params=array()){

        if(Sys::app()->request->isAjax) $this->ajaxLoadHint();

        $error='Обработчику данных Filter переданы неправильные данные. Невозможно создать фильтр.';
        if(!$link || !$name || !is_string($name)){
            Sys::app()->error=$error;
            return false;
        }

        $this->setParams($params);
        //if(self::$ajax) $this->htmlOptions['onchange']='Data.filterChange(this,true)';

        if(is_array($link)){
            foreach($this->htmlOptions as $name){
                if(isset($params[$name])) unset($params[$name]);
            }
            $link=Sys::app()->request->createUrl(Sys::app()->request->route,$link);
        }
        if(!is_string($link)){
            Sys::app()->error=$error;
            return false;
        }

        $value=isset($this->htmlOptions['values'][$name]) && $this->htmlOptions['values'][$name] ? $this->htmlOptions['values'][$name] : '';
        $filterField='<input type="'.$this->htmlOptions['type'].'" data-id="'.$link.'" name="filter['.$name.']" value="'.$value.'"';
        if($this->htmlOptions['elementId']) $filterField.=' id="'.$this->htmlOptions['elementId'].'"';
        if($this->htmlOptions['class']) $filterField.=' class="'.$this->htmlOptions['class'].'"';
        if($this->htmlOptions['onkeyup']) $filterField.=' onkeyup="'.$this->htmlOptions['onkeyup'].'"';
        if($this->htmlOptions['onchange']) $filterField.=' onchange="'.$this->htmlOptions['onchange'].'"';
        $filterField.=' />';

        if($this->htmlOptions['elementId']){
            $inputId=$this->htmlOptions['elementId'];
            $filterField.='<div id="hint-'.$inputId.'" class="list-container filter"></div>';
            Sys::app()->scripts=BASEURL.'framework'.SEP.'views'.SEP.'scripts'.SEP.'dataEventHandler.js';
        }

        return $filterField;
    }

    public function getAttributes()
    {
        $params=array_merge($this->params,Sys::app()->request->params);

        $result=array();
        foreach($params as $name=>$param){
            if(strpos($param,'like')!==false){
                $this->params[$name]=$param;
                $result[$name]=$param;
            }
        }

        return $result;
    }

    public function setModel($model)
    {
        if(is_object($model)) $this->model=$model;
        elseif(is_string($model)) $this->model=Model::model($model);
        else Sys::app()->error='Обработчику Filter передана неправильная модель: это должен быть объект или сторока';
    }

    private function ajaxLoadHint()
    {
        $method=strtolower(Sys::app()->request->method);
        if(!$ajaxData=Sys::app()->request->$method) return;
        $name=isset($ajaxData['filterName']) ? $ajaxData['filterName'] : '';
        $value=isset($ajaxData['filterValue']) ? $ajaxData['filterValue'] : '';
        if(!$name || !$value) return;

        $json=array(
            'content'=>'',
            'error'=>'',
        );

        if(!$this->model) $json['error']=Sys::app()->error='Не перадана модель для обработчика Filter';
        else{
            $requestParams=Sys::app()->request->params;
            foreach($requestParams as $param=>$val){
                if(strpos($val,'like')!==false) unset($requestParams[$param]);
            }

            $result=array();
            $attributes=array_merge($requestParams,array($name=>'like '.$value));

            if($results=$this->model->findAllByAttributes(array($name,'where'=>$attributes))){
                if(is_array($results)){
                    foreach($results as $res){
                        $result[]=$res->$name;
                    }
                }
            }
            unset($results);

            $result=array_filter($result);
            if($result){
                $result=array_unique($result);

                foreach($result as $num=>$res){
                    $attributes[$name]='like '.$res;
                    $res=str_ireplace($value,'<span class="red">'.$value.'</span>',$res);
                    $url=Sys::app()->request->createUrl(Sys::app()->request->route,$attributes);
                    $result[$num]='<p class="list filter" data-id="'.$url.'">'.$res.'</p>';
                }
            }
            if($result) $json['content']=implode('',$result);
        }

        exit(json_encode($json));
    }
}